﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Web;
using Ajax.Model;
using Ajax.Common;
namespace Ajax.BLL
{
    public static class RewriterCache
    {
        private static List<RegexInfo> _regex_list;
        public static List<RegexInfo> ReadRewriterRule(HttpContext context)
        {
            if (CacheHelper.TryGet("Ajax_RewriterCache", out _regex_list) == true)
            {
                return _regex_list;
            }
            else
            {
                _regex_list = new List<RegexInfo>();
                lock (_regex_list)
                {
                    using (XmlTextReader tr = new XmlTextReader(context.Server.MapPath("~/XmlConfig/UrlRewriter.config")))
                    {
                        while (tr.Read())
                        {
                            if (tr.NodeType == XmlNodeType.Element && tr.Name == "URLRewriters")
                            {
                                string NewPath = tr.GetAttribute("NewPath");
                                string RealPath = tr.GetAttribute("RealPath");

                                if (NewPath.StartsWith(@"~/"))
                                    NewPath = string.Concat(context.Request.ApplicationPath, NewPath.Substring(2));
                                if (RealPath.StartsWith(@"~/"))
                                    RealPath = string.Concat(context.Request.ApplicationPath, RealPath.Substring(2));

                                _regex_list.Add(new RegexInfo(NewPath, RealPath, tr.GetAttribute("ReverseNewPath"), tr.GetAttribute("ReverseRealPath")));

                            }
                        }
                    }
                    CacheHelper.Add("Ajax_RewriterCache", _regex_list, CacheHelper.DateTimeType.Day, 1);

                }
            }
            return _regex_list;
        }
    }
}